package com.ruoyi.quartz.service.impl;

import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.quartz.domain.SysJobLog;
import com.ruoyi.quartz.mapper.SysJobLogMapper;
import com.ruoyi.quartz.service.ISysJobLogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * 定时任务调度日志信息 服务层
 *
 * @author ruoyi
 */
@Service
public class SysJobLogServiceImpl implements ISysJobLogService {
    @Autowired
    private SysJobLogMapper jobLogMapper;

    /**
     * 分页获取quartz调度器日志的计划任务
     *
     * @param jobLog 调度日志信息
     * @return 调度任务日志集合
     */
    @Override
    public Page<SysJobLog> selectJobLogPage(SysJobLog jobLog, Page<SysJobLog> page) {
        Map<String, Object> params = jobLog.getParams();
        return getLambdaQueryChainWrapper(jobLog, params)
                .page(page);
    }

    private LambdaQueryChainWrapper<SysJobLog> getLambdaQueryChainWrapper(SysJobLog jobLog, Map<String, Object> params) {
        return new LambdaQueryChainWrapper<>(jobLogMapper)
                .like(StringUtils.isNotEmpty(jobLog.getJobName()), SysJobLog::getJobName, jobLog.getJobName())
                .eq(StringUtils.isNotEmpty(jobLog.getJobGroup()), SysJobLog::getJobGroup, jobLog.getJobGroup())
                .eq(StringUtils.isNotEmpty(jobLog.getStatus()), SysJobLog::getStatus, jobLog.getStatus())
                .ge(params != null && params.get("beginTime") != null, SysJobLog::getCreateTime, params.get("beginTime"))
                .le(params != null && params.get("endTime") != null, SysJobLog::getCreateTime, params.get("endTime"))
                .orderByDesc(SysJobLog::getJobLogId);
    }

    /**
     * 通过调度任务日志ID查询调度信息
     *
     * @param jobLogId 调度任务日志ID
     * @return 调度任务日志对象信息
     */
    @Override
    public SysJobLog selectJobLogById(Long jobLogId) {
        return jobLogMapper.selectById(jobLogId);
    }

    /**
     * 新增任务日志
     *
     * @param jobLog 调度日志信息
     */
    @Override
    public void addJobLog(SysJobLog jobLog) {
        jobLogMapper.insert(jobLog);
    }

    /**
     * 批量删除调度日志信息
     *
     * @param logIds 需要删除的数据ID
     * @return 结果
     */
    @Override
    public int deleteJobLogByIds(Long[] logIds) {
        return jobLogMapper.deleteByIds(List.of(logIds));
    }

    /**
     * 删除任务日志
     *
     * @param jobId 调度日志ID
     */
    @Override
    public int deleteJobLogById(Long jobId) {
        return jobLogMapper.deleteById(jobId);
    }

}
